<template>
  <a-modal title="选择广告计划" v-model:visible="visible" width="1000px">
    <div class="account-plan-container">
      <div class="account-list">
        <h3>账号列表</h3>
        <a-list :dataSource="accountList" :rowKey="(item) => item.id" class="account-list-content">
          <template #renderItem="{ item }">
            <a-list-item :class="{ active: selectedAccountId === item.id }" @click="handleSelectAccount(item)">
              <div class="account-item">
                <div class="account-info">
                  <div class="account-name" :title="item.name">{{ item.name }}</div>
                  <div class="account-id">ID: {{ item.id }}</div>
                </div>
                <a-badge
                  v-if="getAccountSelectedCount(item.id) > 0"
                  :count="getAccountSelectedCount(item.id)"
                  style="margin-left: 8px"
                />
              </div>
            </a-list-item>
          </template>
        </a-list>
      </div>
      <div class="plan-list">
        <h3>计划列表</h3>
        <div v-if="loading" class="loading-container">
          <a-spin />
        </div>
        <div v-else-if="!selectedAccountId" class="empty-tip">请先选择左侧账号</div>
        <a-table
          v-else
          :columns="planColumns"
          :dataSource="planList"
          rowKey="id"
          :pagination="{
            pageSize: pageSize,
            total: totalPlans,
            current: currentPage,
            onChange: handlePageChange,
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '20', '50'],
            onShowSizeChange: handlePageSizeChange,
          }"
          :rowSelection="{
            type: 'checkbox',
            selectedRowKeys: currentAccountSelectedKeys,
            preserveSelectedRowKeys: true,
            onChange: onSelectChange,
            getCheckboxProps: getCheckboxProps,
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'deliveryStatusDisplayName'">
              <a-tag :color="getStatusColor(record.deliveryStatusDisplayName)">
                {{ record.deliveryStatusDisplayName }}
              </a-tag>
            </template>
            <template v-if="column.key === 'budget'"> {{ record.budget }}元/天 </template>
          </template>
        </a-table>
      </div>
    </div>
    <div class="selected-summary" v-if="tempSelectedPlans.length > 0">
      <div>已选择 {{ tempSelectedPlans.length }} 个计划</div>
      <a-button type="link" @click="clearAllSelected">清空所有</a-button>
    </div>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :disabled="tempSelectedPlans.length === 0" @click="handleConfirm" style="margin-left: 8px">
        确定 (已选 {{ tempSelectedPlans.length }} 个)
      </a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { message } from "ant-design-vue";

import { batchCreateAdStore } from "@/pages/NewBatchCreateAd/store/batchCreateAdStore";

const store = batchCreateAdStore();

// 定义 props，接收父组件传递的已选计划
const props = defineProps({
  selectedPlans: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:visible", "select"]);
const visible = ref(false);
const loading = ref(false);
// 初始化为空数组，完全依赖 store 提供的账号列表
const accountList = ref([]);

// 在组件挂载时从 store 获取账号列表
onMounted(() => {
  if (store.AccountItems && store.AccountItems.length > 0) {
    accountList.value = store.AccountItems;
  } else {
    // 如果 store 中没有账号，使用默认账号（仅用于开发测试）
    accountList.value = [
      { id: 1, name: "广告账号A" },
      { id: 2, name: "广告账号B" },
    ];
  }
});

const selectedAccountId = ref(null);
const planList = ref([]);
const allSelectedPlans = ref([]); // 实际已选计划（确认后的）
const tempSelectedPlans = ref([]); // 临时选择的计划（未确认）
const currentPage = ref(1);
const pageSize = ref(5);
const totalPlans = ref(0);

// 计算当前账号选中的计划ID
const currentAccountSelectedKeys = computed(() => {
  return tempSelectedPlans.value.filter((plan) => Math.floor(plan.id / 100) === selectedAccountId.value).map((plan) => plan.id);
});

// 修改列定义，只显示计划名称、预算和投放状态
const planColumns = [
  { title: "ID", dataIndex: "id", key: "id", width: "80px" },
  { title: "计划名称", dataIndex: "name", key: "name" },
  { title: "预算", dataIndex: "budget", key: "budget", width: "120px" },
  { title: "状态", dataIndex: "deliveryStatusDisplayName", key: "deliveryStatusDisplayName", width: "100px" },
];

const show = () => {
  visible.value = true;

  // 从父组件获取最新的已选计划
  if (props.selectedPlans && Array.isArray(props.selectedPlans)) {
    // 始终使用父组件传递的最新数据
    allSelectedPlans.value = JSON.parse(JSON.stringify(props.selectedPlans));
    tempSelectedPlans.value = JSON.parse(JSON.stringify(props.selectedPlans));
  } else {
    // 如果没有传递计划，则清空
    allSelectedPlans.value = [];
    tempSelectedPlans.value = [];
  }

  // 只重置账号选择，不清空已选计划
  if (!selectedAccountId.value && accountList.value.length > 0) {
    selectedAccountId.value = accountList.value[0].id;
    currentPage.value = 1;
    fetchPlanList(selectedAccountId.value, 1);
  } else if (selectedAccountId.value) {
    // 如果已有选中账号，刷新当前页数据
    fetchPlanList(selectedAccountId.value, currentPage.value);
  }
};

const hide = () => {
  visible.value = false;
};

const handleCancel = () => {
  // 取消时不保存临时选择
  hide();
};

const getData = () => {
  return allSelectedPlans.value;
};

// 获取指定账号已选计划数量
const getAccountSelectedCount = (accountId) => {
  return tempSelectedPlans.value.filter((plan) => Math.floor(plan.id / 100) === accountId).length;
};

// 处理账号选择
const handleSelectAccount = (account) => {
  if (selectedAccountId.value === account.id) return; // 避免重复点击

  selectedAccountId.value = account.id;
  currentPage.value = 1; // 切换账号时重置为第一页
  fetchPlanList(account.id, 1);
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchPlanList(selectedAccountId.value, page);
};

// 处理每页数量变化
const handlePageSizeChange = (current, size) => {
  pageSize.value = size;
  currentPage.value = 1; // 改变每页数量时重置为第一页
  fetchPlanList(selectedAccountId.value, 1);
};

// 获取计划列表
const fetchPlanList = (accountId, page = 1) => {
  if (!accountId) return;

  loading.value = true;
  // 模拟API请求
  setTimeout(() => {
    // 设置总计划数
    totalPlans.value = accountId * 15; // 每个账号有不同数量的计划

    // 根据账号ID和页码生成不同的计划数据
    const plans = [];
    const startIndex = (page - 1) * pageSize.value;
    const endIndex = Math.min(startIndex + pageSize.value, totalPlans.value);

    // 状态列表
    const statusList = ["投放中", "暂停", "已结束"];

    for (let i = startIndex; i < endIndex; i++) {
      const planId = accountId * 100 + i + 1;
      plans.push({
        id: planId,
        name: `计划${accountId}-${i + 1}`,
        budget: 500 + i * 100,
        deliveryStatusDisplayName: statusList[i % 3],
      });
    }

    planList.value = plans;
    loading.value = false;
  }, 500);
};

// 处理计划选择
const onSelectChange = (selectedKeys, selectedRows) => {
  // 获取当前账号的所有计划ID
  const currentAccountPlanIds = planList.value.map((plan) => plan.id);

  // 移除当前账号中已取消选择的计划
  tempSelectedPlans.value = tempSelectedPlans.value.filter((plan) => {
    // 如果不是当前账号的计划，保留
    if (Math.floor(plan.id / 100) !== selectedAccountId.value) {
      return true;
    }
    // 如果是当前账号的计划，只保留仍在选中状态的
    return selectedKeys.includes(plan.id);
  });

  // 添加新选中的计划
  // 确保selectedRows中的每个元素都是有效的对象
  if (Array.isArray(selectedRows)) {
    selectedRows.forEach((row) => {
      // 检查row是否为有效对象且具有id属性
      if (row && typeof row === "object" && "id" in row) {
        // 检查是否已存在
        const exists = tempSelectedPlans.value.some((plan) => plan.id === row.id);
        if (!exists) {
          tempSelectedPlans.value.push(row);
        }
      }
    });
  }
};

// 清空所有已选计划
const clearAllSelected = () => {
  tempSelectedPlans.value = [];
  if (selectedAccountId.value) {
    fetchPlanList(selectedAccountId.value, currentPage.value);
  }
};

// 获取状态标签颜色
const getStatusColor = (status) => {
  switch (status) {
    case "投放中":
      return "green";
    case "暂停":
      return "orange";
    case "已结束":
      return "red";
    default:
      return "blue";
  }
};

// 确认选择
const handleConfirm = () => {
  if (tempSelectedPlans.value.length === 0) {
    message.error("请至少选择一个计划");
    return;
  }

  // 获取所有账号ID
  const allAccountIds = accountList.value.map((account) => account.id);

  // 检查每个账号是否都选择了计划
  const accountsWithoutPlans = allAccountIds.filter((accountId) => {
    return tempSelectedPlans.value.filter((plan) => Math.floor(plan.id / 100) === accountId).length === 0;
  });

  if (accountsWithoutPlans.length > 0) {
    const accountNames = accountList.value
      .filter((account) => accountsWithoutPlans.includes(account.id))
      .map((a) => a.name)
      .join("、");

    message.error(`以下账号未选择计划: ${accountNames}`);
    return;
  }

  // 将临时选择保存为实际选择
  allSelectedPlans.value = JSON.parse(JSON.stringify(tempSelectedPlans.value));
  emit("select", allSelectedPlans.value);
  hide();
};

// 添加更新已选计划的方法
const updateSelectedPlans = (plans) => {
  if (Array.isArray(plans)) {
    allSelectedPlans.value = JSON.parse(JSON.stringify(plans));

    // 如果弹窗打开中，也更新临时选择
    if (visible.value) {
      tempSelectedPlans.value = JSON.parse(JSON.stringify(plans));
    }
  }
};

// 获取复选框属性
const getCheckboxProps = (record) => {
  return {
    disabled: false, // 可以根据需要设置禁用条件
    name: record.id.toString(),
  };
};

// 添加更新账号列表的方法
const updateAccountList = (accounts) => {
  if (Array.isArray(accounts) && accounts.length > 0) {
    accountList.value = accounts;

    // 如果当前选中的账号不在新的账号列表中，重置选中账号
    if (selectedAccountId.value) {
      const accountExists = accounts.some((acc) => acc.id === selectedAccountId.value);
      if (!accountExists && accounts.length > 0) {
        selectedAccountId.value = accounts[0].id;
        currentPage.value = 1;
        fetchPlanList(accounts[0].id, 1);
      }
    }

    // 过滤临时选择的计划，移除不存在账号的计划
    const accountIds = new Set(accounts.map((acc) => acc.id));
    tempSelectedPlans.value = tempSelectedPlans.value.filter((plan) => {
      const planAccountId = Math.floor(plan.id / 100);
      return accountIds.has(planAccountId);
    });

    // 同步到实际选择
    allSelectedPlans.value = JSON.parse(JSON.stringify(tempSelectedPlans.value));
  }
};

// 暴露给父组件的方法
defineExpose({
  show,
  hide,
  getData,
  updateSelectedPlans,
  updateAccountList,
});
</script>

<style scoped>
.account-plan-container {
  display: flex;
  height: 400px;
}

.account-list {
  width: 250px;
  border-right: 1px solid #f0f0f0;
  padding-right: 16px;
  overflow-x: auto;
  overflow-y: auto;
}

.account-list-content {
  height: calc(100% - 40px);
  overflow-y: auto;
}

.account-item {
  cursor: pointer;
  width: 100%;
  display: flex;
  align-items: center;
  overflow: hidden;
  padding: 0 8px;
}

.account-info {
  flex: 1;
  overflow: hidden;
}

.account-name {
  font-weight: bold;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.account-id {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}

.plan-list {
  flex: 1;
  padding-left: 16px;
  overflow-y: auto;
}

.loading-container,
.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100% - 40px);
  color: #999;
}

.active {
  background-color: #e6f7ff;
  border-right: 3px solid #1890ff;
}

.selected-summary {
  margin-top: 16px;
  padding: 8px 16px;
  background-color: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
}

.selected-summary div {
  flex: 1;
}
</style>
